import type { AccidentResult, ConstructionResult, AlarmResult, VioSurveilResult, Monitor } from '../service/api/type'

type DataType = 'accident' | 'construction' | 'alarm' | 'vioSurveil' | 'monitor' | 'deathAccident';

interface WorkerMessage {
  data: AccidentResult[] | ConstructionResult[] | AlarmResult[] | VioSurveilResult[] | Monitor[];
  type: DataType;
}

interface BatchResult {
  position: string;
  image: string;
}

const getPosition = (
  element: AccidentResult | ConstructionResult | AlarmResult | VioSurveilResult | Monitor,
  type: DataType
): string => {
  switch (type) {
    case "accident":
    case "deathAccident":
      return (element as AccidentResult).dzzb;
    case "construction": {
      const constructionElement = element as ConstructionResult;
      return `${constructionElement.constructionPointLongitude},${constructionElement.constructionPointLatitude}`;
    }
    case "alarm": {
      const alarmElement = element as AlarmResult;
      return `${alarmElement.occurPlaceLongitude},${alarmElement.occurPlaceLatitude}`;
    }
    case "vioSurveil": {
      const vioElement = element as VioSurveilResult;
      return vioElement.jd && vioElement.wd ? `${vioElement.jd},${vioElement.wd}` : "";
    }
    case "monitor": { //监控
      const monitorElement = element as Monitor;
      return monitorElement.jd && monitorElement.wd ? `${monitorElement.jd},${monitorElement.wd}` : "";
    }
    default:
      return "";
  }
}

// 监听主线程消息
self.addEventListener('message', (e: MessageEvent<WorkerMessage>) => {
  const { data, type } = e.data;

  // 分批处理数据
  const batchSize = 100;
  const results: BatchResult[] = [];

  for (let i = 0; i < data.length; i += batchSize) {

    const batch = data.slice(i, i + batchSize);

    const batchResults = batch.map(element => {
      const position = getPosition(element, type);
      return position ? { position, image: type as string, ...element } : null;
    }).filter((result): result is { position: string; image: string } => result !== null);

    results.push(...batchResults);

    // 每处理完一批数据就发送回主线程
    if (batchResults.length > 0) {
      self.postMessage({
        type: 'batch',
        data: batchResults,
      });
    }
  }

  // 发送处理完成的消息
  self.postMessage({
    type: 'complete',
    data: results.length
  });
});
